define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/dialog",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "static/app/fxpg/util/js/bootstrap-select",
    "static/app/fxpg/util/js/defaults-zh_CN",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, Dialog, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxPreestimateReport";

    var fxPreestimateReportFormHtml = sysPath + "/views/fxPreestimateReportForm.html";
    var getFxPreestimateReportController = function () {
        return getServer() + "/fx/fxPreestimateReports";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        initUnitSelect();
        queryBtnBind();
        createFxPreestimateReportGrid();
    };

    var initUnitSelect = function () {
        $.ajax({
            url: getServer() + "/depts/"+ "ZFZX",
            type: "get",
            success: function (data) {
                console.log(data)
                debugger
                var html = "";
                for (var i = 0; i < data.length; i++) {
                    html += "<option value='" + data[i].deptName + "'>" + data[i].deptName + "</option>";
                }
                $("#unitSelect").append(html);
                $('.selectpicker').selectpicker({'selectedText': 'cat'});
            }
        });
    };
    var initUnitForm = function () {
        $.ajax({
            url: getServer() + "/depts/" + "ZFZX",
            type: "get",
            success: function (data) {
                console.log(data)
                debugger
                var html = "";
                for (var i = 0; i < data.length; i++) {
                    html += "<option value='" + data[i].deptName + "'>" + data[i].deptName + "</option>";
                }
                $("#unit").append(html);
                $('.selectpicker').selectpicker({'selectedText': 'cat'});
            }
        });
    };


    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
        require(["jquery", "Date", "DateCN", "css!DateCss"], function ($) {
            $("#yearStart").datetimepicker({
                //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
                language: "cn",
                //输出格式化
                format: 'yyyy',
                //直接选择‘今天’
                todayBtn: true,
                weekStart: 1,
                // 设置最精确的时间选择视图
                startView: 4,
                //设置最精确的时间选择视图
                minView: 4,
//              minView: 'month',
                //高亮当天日期
                todayHighlight: true,
                //选择完毕后自动关闭
                autoclose: true
            });


            $("#yearEnd").datetimepicker({
                //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
                language: "cn",
                //输出格式化
                format: 'yyyy',
                weekStart: 1,
                // 设置最精确的时间选择视图
                startView: 4,
                //直接选择‘今天’
                todayBtn: true,
                //设置最精确的时间选择视图
                minView: 4,
                //minView: 'month',
                //高亮当天日期
                todayHighlight: true,
                //选择完毕后自动关闭
                autoclose: true
            });

        })
    };
    var queryBtnBind = function () {
    	$("#yearStart").change(function () {
            if ($("#yearStart").val() != "" && $("#yearEnd").val() != "") {
                if ($("#yearStart").val() > $("#yearEnd").val()) {
                    Util.alert("开始年度必须小于等于结束年度", function () {
                        $("#yearStart").val("");
                        $("#yearEnd").val("");
                    });
                    return;
                }
            }
        });
        $("#yearEnd").change(function () {
            if ($("#yearStart").val() != "" && $("#yearEnd").val() != "") {
                if ($("#yearStart").val() > $("#yearEnd").val()) {
                    Util.alert("开始年度必须小于等于结束年度", function () {
                        $("#yearStart").val("");
                        $("#yearEnd").val("");
                    });
                    return;
                }
            }
        });
        $("#btnSearch").click(function () {
            createFxPreestimateReportGrid();
        });
        $("#btnReset").click(function () {
            $("#workspaceCondition").val("");
            $("#yearStart").val("");
            $("#yearEnd").val("");
            $('#unitSelect').selectpicker('val', []);
        });
    };

    var createFxPreestimateReportGrid = function () {
        let unit = "";
        if ($("#unitSelect").val() != null) {
            // 数组转字符串
            unit = $("#unitSelect").val().toString();
        }
        $("#fxPreestimateReportGrid").datagrid({
            url: getFxPreestimateReportController() + "/queryFxPreestimateReports",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            nowrap: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'workspace',
                    title: '工作区名称',
                    width: '14%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editFxPreestimateReport(\'' + rowData.id + '\');"> ' + rowData.workspace + ' </a> '
                    }
                },
                {
                    field: 'year',
                    title: '年度',
                    width: '15%',
                    align: 'center',
                },
                {
                    field: 'unit',
                    title: '编制单位（多个省局以‘,’分隔）',
                    width: '25%',
                    align: 'center',
                },
                {
                    field: 'reportBriefName',
                    title: '报告（简本）',
                    width: '15%',
                    align: 'center',
                },
                {
                    field: 'reportDetailName',
                    title: '报告（详本）',
                    width: '15%',
                    align: 'center',
                },
                {
                    field: 'reportName',
                    title: '报告',
                    width: '15%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "添加",
                handler: function () {
                    addFxPreestimateReport();
                }
            }, {
                iconCls: 'fa fa-plus-circle',
                text: "模板",
                handler: function () {
                    downloadTemplate();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "文件批量导入",
                handler: function () {
                    upload();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importForm();
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteFxPreestimateReport();
                }
            }],
            queryParams: {
                workspace: $("#workspaceCondition").val(),
                yearStart: $("#yearStart").val(),
                yearEnd: $("#yearEnd").val(),
                unit: unit,
            },
            pagination: true,
            pageSize: 10
        });
    };
    var formValidator = function () {
        $("#fxPreestimateReportForm").validate({
            rules: {
                workspace: {
                    required: true,
                },
                year: {
                    required: true,
                },
                unit: {
                    required: true,
                },
            },
            messages: {
                workspace: {
                    required: "工作区名称不允许为空!",
                },
                year: {
                    required: "年度不允许为空!",
                },
                unit: {
                    required: "编制单位（多个省局以‘、’分隔）不允许为空!",
                },
            }
        });
    };

    var getFxPreestimateReport = function (id) {
        $.ajax({
            url: getFxPreestimateReportController() + "/" + id,
            type: "get",
            success: function (data) {

                debugger
                data.unit = data.unit.split(",");
                Tool.deserialize("fxPreestimateReportForm", data);
                $('#unit').selectpicker('val', data.unit);
                // 报告文件
                viewFileUpload(data.reportBriefId, data.reportBriefName, "reportBrief", "multiFileUpload");
                viewFileUpload(data.reportDetailId, data.reportDetailName, "reportDetail", "multiFileUpload2");
                viewFileUpload(data.reportId, data.reportName, "report", "multiFileUpload3");
            }
        });
    };

    /**
     * 添加
     */
    var addFxPreestimateReport = function () {
        var slidebar = Util.slidebar({
            url: fxPreestimateReportFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                // 添加显示单位
                initUnitForm();
                // $('.selectpicker').selectpicker();
                // 报告文件
                fileUpload("reportBriefId", "reportBriefName", "multiFileUpload");
                fileUpload("reportDetailId", "reportDetailName", "multiFileUpload2");
                fileUpload("reportId", "reportName", "multiFileUpload3");
                // 点击保存
                $("#saveBtn").on("click", function () {
                    if ($("#fxPreestimateReportForm").valid()) {
                        var data = Tool.serialize("fxPreestimateReportForm");
                        data.unit = data.unit.toString();
                        console.log(data)
                        $.ajax({
                            url: getFxPreestimateReportController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxPreestimateReportGrid();
                            }
                        });
                    }
                });
            }
        });
    };

    // 下载模板
    var downloadTemplate = function () {
        window.location.href = getServer() + "/excel/预评估报告模板.xlsx";
    };

    // 文件批量导入
    window.upload = function () {
        debugger;
        var buttons = [];
        buttons.push({
            name: '确定',
            callback: function () {
                //点击确定
                debugger;
                dialog.hide();
            }
        });
        var dialog = Dialog({
            id: "viewTeamDialog",
            cache: false,
            title: '上传附件', //dialog标题
            width: "900px",
            height: "350px",
            body: '<div id="TeamGrid">' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<label for="detailFile" class="col-md-2 control-label">文档:</label>' +
                '<div class="col-md-10" id="multiFileUpload">' +
                '<input id="detailFile" type="hidden" name="detailFile" class="form-control"  />' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>',
            buttons: buttons,
            afterOpen: function () {
                fileUpload("detailFile", "", "multiFileUpload");
            }
        });
        dialog.show();
    };

    // 导入
    var importForm = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/预评估报告模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxPreestimateReportController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    // 刷新列表
                    createFxPreestimateReportGrid();
                    Util.alert(data);
                }
            });
        });
    };

    /**
     * 编辑
     * @param fxPreestimateReportId
     * @private
     */
    window._editFxPreestimateReport = function (fxPreestimateReportId) {
        var slidebar = Util.slidebar({
            url: fxPreestimateReportFormHtml,
            width: "880px",
            cache: false,
            close: true,
            afterLoad: function () {
                // 编辑回显单位
                initUnitForm();
                formValidator();
                getFxPreestimateReport(fxPreestimateReportId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxPreestimateReportForm").valid()) {
                        var data = Tool.serialize("fxPreestimateReportForm");
                        data.unit = data.unit.toString();
                        $.ajax({
                            url: getFxPreestimateReportController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxPreestimateReportGrid();
                            }
                        });
                    }
                });
            }
        });
    };

    /**
     * 删除
     */
    var deleteFxPreestimateReport = function () {
        var rows = $("#fxPreestimateReportGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxPreestimateReportController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxPreestimateReportGrid();
                }
            });
        }, function () {
            return;
        });

    };

    //------------------------------------附件接口---------------------------------------//

    /**
     * 上传附件
     * @param fileId 文件id
     * @param fileName 文件name
     * @param placeAt
     */
    var fileUpload = function (fileId, fileName, placeAt) {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachId = "";
            var attachName = "";
            var settings = {
                placeAt: placeAt,
                allowMC:false,
    			fileSizeLimit: 200*1024*1024,
                /*
	            1.0.2版本新增
	            extendColumn:[
	                {name:"文件分类",filed:"category",format:function(file){return file.name}},
	                {name:"备注",filed:"remark",format:function(file){return '机密'}}
	            ],*/
                //data:["5a50d697c0af806aa01e06120d04f977","6c01e4492f264befab4c0532811f8dff"],
                onUploadSuccess: function (file) {
                    console.log(file);
                    debugger
                    attachId += file.attachId + ",";
                    attachName += file.name + ",";
                    $("#" + fileId).val(attachId.substr(0, attachId.length - 1));
                    $('#' + fileName).val(attachName.substr(0, attachName.length - 1));
                },
                onDeleteSavedFile: function (file) {
                    //console.log(file)
                }
            };
            MFU.init(settings);
        });
    };

    /**
     * 编辑-查看文件
     * @param fileId 附件iD
     * @param fileName 附件名称
     * @param classId 附件class类ID
     * @param placeAt
     */
    var viewFileUpload = function (fileId, fileName, classId, placeAt) {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachIdData = "";
            var attachId = "";
            var attachName = "";
            debugger;
            var fileArray = "";
            var fileNameArray = "";
            if (fileId != null && fileId.length != 0) {
                fileArray = fileId.split(',');
                attachIdData = fileId.split(',');
                fileNameArray = fileName.split(',');
            }
            var settings = {
                placeAt: placeAt,
                allowMC:false,
    			fileSizeLimit: 200*1024*1024,
                /*
	            1.0.2版本新增
	            extendColumn:[
	                {name:"文件分类",filed:"category",format:function(file){return file.name}},
	                {name:"备注",filed:"remark",format:function(file){return '机密'}}
	            ],*/
                data: attachIdData,
                onUploadSuccess: function (file) {
                    attachId += file.attachId + ",";
                    attachName += file.name + ",";
                    if (fileId.length == 0) {
                        $("#" + classId + "Id").val(attachId.substr(0, attachId.length - 1));
                        $("#" + classId + "Name").val(attachName.substr(0, attachName.length - 1));
                    } else {
                        $("#" + classId + "Id").val(fileId + "," + attachId.substr(0, attachId.length - 1));
                        $("#" + classId + "Name").val(fileName + "," + attachName.substr(0, attachName.length - 1));
                    }
                },
                onDeleteSavedFile: function (file) {
                    var index = fileArray.indexOf(file.attachId);
                    fileArray.splice(index, 1);
                    var number = fileNameArray.indexOf(file.attachName);
                    fileNameArray.splice(number, 1);
                    $("#" + classId + "Id").val(fileArray.toString());
                    $("#" + classId + "Name").val(fileNameArray.toString());
                }
            };
            MFU.init(settings);
        });
    };

    return {
        init: init
    };
});
